const loginDao = require('../dao/login');

const config = require('../config').config;

const Response = require('../entity/http/Response');

const { createUserJwtToken } = require('../utils/token');

const loginService = {
    async login(reqId, uid, { account, password }) {
        let result;
        try {
            let data = await loginDao.login(account, password);
            console.log(`[ INFO ] [ req-id = ${ reqId } ] [ Service ] 查询结果 ${ JSON.stringify(data) }`);
            if (data.length) {
                let user = data[0];
                // 生成 token
                let payload = { uid: user.id };
                let jwt = await createUserJwtToken(payload, { expiresIn: config.token_exp });
                console.log(`[ INFO ] [ req-id = ${ reqId } ] [ Service ] 生成token ${ jwt }`);
                // 响应
                result = new Response().success({ token: jwt, userInfo: {
                    uid: user.id,
                    userTypeId: user.userTypeId,
                    userType: user.userType,
                    name: user.name,
                    phone: user.phone
                } });
            } else {
                result = new Response().fail(401, '用户名或密码错误');
            }
        } catch (err) {
            result = new Response().fail(500, '服务器错误');
        }
        return result;
    }
};

module.exports = loginService;